//leetcode24

struct ListNode {
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if (head == nullptr || head->next == nullptr)
            return head;
        ListNode* prev = head;
        ListNode* cur = head->next;
        ListNode* Cnext = cur->next;
        ListNode* last = nullptr;
        head = head->next;
        while (prev != nullptr && prev->next != nullptr)
        {
            cur = prev->next;
            Cnext = cur->next;
            if (last != nullptr)
                last->next = cur;
            cur->next = prev;
            prev->next = Cnext;
            last = prev;
            prev = Cnext;
        }
        return head;
    }
};